package com.suxin.rpc;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;
import java.util.concurrent.Callable;

/**
 * @author Tang
 * @classname NettyClientHandler
 * @description [ TODO ]
 * @date 2021/1/17 20:21
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter implements Callable<Object> {

    private String params;

    private String result;

    private ChannelHandlerContext handlerContext;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("client channelActive...");
        handlerContext = ctx;
        System.out.println("handlerContext--->" + handlerContext);
    }

    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        result = msg.toString();
        System.out.println(result);
        notify();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public synchronized Object call() throws Exception {
        System.out.println("handlerContext--->" + handlerContext);
        handlerContext.writeAndFlush(Unpooled.copiedBuffer(params,Charset.defaultCharset()));
        System.out.println("call....");
        wait();
        return result;
    }

    public void setParams(String params) {
        this.params = params;
    }
}